/*
JuffEd - A simple text editor
Copyright 2007 Murzin Mikhail

This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License 
version 2 as published by the Free Software Foundation.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
*/

#include "LineNumWidget.h"

//	Local
#include "TextDocSettings.h"

//	Qt
#include <QtGui/QPainter>
#include <QtGui/QTextBlock>
#include <QtGui/QTextEdit>

#include <math.h>

LineNumWidget::LineNumWidget(QTextEdit* ed, QWidget* parent) : 
	QWidget(parent), 
	ed_(ed),
	indent_(10) {
        
        setAcceptDrops(false);

}

void LineNumWidget::updateWidget() {
	int rowCount = ed_->document()->blockCount();
	int digits = int(log10(float(rowCount))) + 1;
	int w = 0;
	if (TextDocSettings::showLineNumbers())
		w = QFontMetrics(TextDocSettings::font()).width("0") * digits + indent_;
	resize(w, height());

	update();
}

void LineNumWidget::paintEvent(QPaintEvent*) {
	QPainter p(this);
	p.setFont(font_);
	p.setPen(Qt::black);
	p.setBrush(QColor(250, 250, 250));
	p.drawRect(rect());
	QTextBlock bl = ed_->document()->begin();
	int w = width() - indent_;
	int h = height();
	while (bl.isValid()) {
		QTextCursor cur(bl);
		QRect rc(ed_->cursorRect(cur));
		int y = rc.y();
		int rc_h = rc.height();
		if (y > h)
			break;
		if (y >= -rc_h)
			p.drawText(indent_, y, w, rc_h, Qt::AlignRight | Qt::AlignBottom, QString::number(cur.blockNumber() + 1));
		bl = bl.next();
	}
}

void LineNumWidget::applySettings() {
	font_ = TextDocSettings::font();
	repaint();
}
